package cn.doctorpda.conference.presenter;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import cn.doctorpda.conference.bean.Msg;
import cn.doctorpda.conference.bean.User;
import cn.doctorpda.conference.bean.checkmeeting.UserIcon;
import cn.doctorpda.conference.config.AppConfig;
import cn.doctorpda.conference.config.NetConfig;
import cn.doctorpda.conference.localstore.UserInfo;
import cn.doctorpda.conference.model.GetChangeHeadModel;
import cn.doctorpda.conference.model.IPostFileModel;
import cn.doctorpda.conference.okhttp.callback.StringCallback;
import cn.doctorpda.conference.utils.AESUtil;
import cn.doctorpda.conference.utils.GsonUtil;
import cn.doctorpda.conference.utils.L;
import cn.doctorpda.conference.view.callbackview.IChangeHeadView;
import okhttp3.Call;

/**
 * Created by huangjinlong on 2016/5/19.
 */
public class ChangeHeadPresenter {
    private IPostFileModel model;
    private IChangeHeadView changeHeadView;
    private UserIcon userInfo=null;

    public ChangeHeadPresenter(IChangeHeadView baseView) {
        model = new GetChangeHeadModel();
        changeHeadView = (IChangeHeadView) baseView;
    }

    public void getChangeHeadData(String mobile, String name, String filename, File file) {
        model.postNetWorkFileData(NetConfig.GET_CHANGE_AVATAR, new StringCallback() {
            @Override
            public void onError(Call call, Exception e) {
                changeHeadView.setNewHeadError(call, e);
            }

            @Override
            public void onResponse(String response) {
                Msg msg = GsonUtil.fromJson(response, Msg.class);
                changeHeadView.setNewResult(msg);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(response);
                    if (jsonObject.getString("encrpt_flag").equals("1")) {

                        String data = AESUtil.decrypt(msg.getData(), AppConfig.AES_KEY);
                        JSONObject object = new JSONObject(data);
                        L.d(object.getString("account").toString());
                        userInfo = GsonUtil.fromJson(object.getString("account").toString(), UserIcon.class);
                        changeHeadView.setNewHeadView(msg, userInfo);
                        L.d("找头像" + userInfo.toString());
                    } else {
                        userInfo = GsonUtil.fromJson(jsonObject.getString("account").toString(), UserIcon.class);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        },  name, filename, file,mobile);
    }
}
